﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Aspose.Cells;
using Mapster;
using Microsoft.AspNetCore.Mvc;
using SHZY.Business.Entitys.Dto.customerfile;
using SHZY.Business.Interfaces;
using SHZY.Common.Core.Manager;
using SHZY.Common.Core.Security;
using SHZY.Common.Enum;
using SHZY.Common.Filter;
using SHZY.DependencyInjection;
using SHZY.DynamicApiController;
using SHZY.FriendlyException;
using SHZY.Systems.Interfaces.System;
using SqlSugar;

namespace SHZY.Business
{
    /// <summary>
    /// 业务实现：客诉文件表.
    /// </summary>
    [ApiDescriptionSettings(Tag = "Business", Name = "QmsBusiCustomerFile", Order = 200)]
    [Route("api/Business/[controller]")]
    public class QmsBusiCustomerFileService : IQmsBusiCustomerFileService, IDynamicApiController, ITransient
    {
        /// <summary>
        /// 服务基础仓储.
        /// </summary>
        private readonly ISqlSugarRepository<QmsBusiCustomerFileEntity> _repository;

        /// <summary>
        /// 数据接口服务.
        /// </summary>
        private readonly IDataInterfaceService _dataInterfaceService;

        /// <summary>
        /// 用户管理.
        /// </summary>
        private readonly IUserManager _userManager;

        private readonly ITenant _db;

        /// <summary>
        /// 初始化一个<see cref="QmsBusiCustomerFileService"/>类型的新实例.
        /// </summary>
        public QmsBusiCustomerFileService(
            ISqlSugarRepository<QmsBusiCustomerFileEntity> qmsBusiCustomerFileRepository,
            IDataInterfaceService dataInterfaceService,
            ISqlSugarClient context,
            IUserManager userManager)
        {
            _repository = qmsBusiCustomerFileRepository;
            _dataInterfaceService = dataInterfaceService;
            _userManager = userManager;
            _db = context.AsTenant();
        }

        /// <summary>
        /// 获取客诉文件表.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<dynamic> GetInfo(string id)
        {
            var data = (await _repository.FirstOrDefaultAsync(x => x.Id == id)).Adapt<QmsBusiCustomerFileInfoOutput>();
            return data;
        }

        /// <summary>
        /// 获取文件列表
        /// </summary>
        /// <returns></returns>
        //[HttpPost("GetInfoList")]
        //public async Task<dynamic> GetInfoList(string customerid)
        //{
        //    var datalist = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1&&it.Type==0 && it.CustomerId == customerid).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
        //    return datalist;
        //}

        /// <summary>
        /// 新建客诉文件表.
        /// </summary>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPost("")]
        public async Task<dynamic> Create([FromBody] QmsBusiCustomerFileCrInput input)
        {
            try
            {
                _db.BeginTran();
                var entity = input.Adapt<QmsBusiCustomerFileEntity>();
                entity.Id = SnowflakeIdHelper.NextId();
                entity.CreatorUserId = _userManager.UserId;
                var isOk = await _repository.Context.Insertable(entity).IgnoreColumns(ignoreNullColumn: true).CallEntityMethod(m => m.Creator()).ExecuteCommandAsync();
                ////不合格图片集合
                List<QmsBusiCustomerFileInfoOutput> imagelist = new List<QmsBusiCustomerFileInfoOutput>();
                List<QmsBusiCustomerFileInfoOutput> datalist = new List<QmsBusiCustomerFileInfoOutput>();
                List<QmsBusiCustomerFileInfoOutput> imagelist2 = new List<QmsBusiCustomerFileInfoOutput>();
                var image = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 0 && it.CustomerId == input.customerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
                var image2 = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 3 && it.CustomerId == input.customerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
                var data = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 1 && it.CustomerId == input.customerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
                foreach (var item in image)
                {
                    imagelist.Add(item);
                }
                foreach (var item in image2)
                {
                    imagelist2.Add(item);
                }
                foreach (var item in data)
                {
                    datalist.Add(item);
                }
                if (!(isOk > 0))
                {
                    _db.RollbackTran();
                    throw Oops.Oh(ErrorCode.COM1000);
                }
                else
                {
                    _db.CommitTran();
                    return new { ImageList = imagelist, ImageList2= imagelist2, DataList = data };
                }
            }
            catch (Exception ex)
            {
                _db.RollbackTran();
                throw Oops.Bah("错误信息：" + ex);
            }

        }

        /// <summary>
        /// 删除客诉文件表.
        /// </summary>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<dynamic> Delete(string id)
        {
            var isOk = await _repository.Context.Updateable<QmsBusiCustomerFileEntity>().SetColumns(it => new QmsBusiCustomerFileEntity() { DeleteMark = 1, DeleteTime = DateTime.Now, DeleteUserId = _userManager.UserId }).Where(it => it.Id.Equals(id)).ExecuteCommandAsync();
            ////不合格图片集合
            List<QmsBusiCustomerFileInfoOutput> imagelist = new List<QmsBusiCustomerFileInfoOutput>();
            List<QmsBusiCustomerFileInfoOutput> datalist = new List<QmsBusiCustomerFileInfoOutput>();
            List<QmsBusiCustomerFileInfoOutput> imagelist2 = new List<QmsBusiCustomerFileInfoOutput>();
            var customerid = await _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.Id == id).Select(it => new QmsBusiCustomerFileEntity() { CustomerId = it.CustomerId }).FirstAsync();
            var image = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 0 && it.CustomerId == customerid.CustomerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
            var image2 = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 3 && it.CustomerId == customerid.CustomerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
            var data = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 1 && it.CustomerId == customerid.CustomerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
            foreach (var item in image)
            {
                imagelist.Add(item);
            }
            foreach (var item in image2)
            {
                imagelist2.Add(item);
            }
            foreach (var item in data)
            {
                datalist.Add(item);
            }
            if (!(isOk > 0)) throw Oops.Oh(ErrorCode.COM1002);
            return new { ImageList = imagelist, ImageList2= imagelist2, DataList = data };
        }


        /// <summary>
        /// 更新客诉文件表.
        /// </summary>
        /// <param name="id">主键值.</param>
        /// <param name="input">参数.</param>
        /// <returns></returns>
        [HttpPut("{id}")]
        public async Task<dynamic> Update(string id, [FromBody] QmsBusiCustomerFileUpInput input)
        {
            try
            {
                var entity = input.Adapt<QmsBusiCustomerFileEntity>();
                var isOk = await _repository.Context.Updateable(entity).UpdateColumns(it => new
                {
                    it.FileInfo,
                    it.Type,
                    it.Remark,
                }).ExecuteCommandAsync();
                ////不合格图片集合
                List<QmsBusiCustomerFileInfoOutput> imagelist = new List<QmsBusiCustomerFileInfoOutput>();
                List<QmsBusiCustomerFileInfoOutput> datalist = new List<QmsBusiCustomerFileInfoOutput>();
                List<QmsBusiCustomerFileInfoOutput> imagelist2 = new List<QmsBusiCustomerFileInfoOutput>();
                var image = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 0 && it.CustomerId == input.customerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
                var image2 = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 3 && it.CustomerId == input.customerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
                var data = _repository.Context.Queryable<QmsBusiCustomerFileEntity>().Where(it => it.DeleteMark == null && it.EnabledMark == 1 && it.Type == 1 && it.CustomerId == input.customerId).ToList().Adapt<List<QmsBusiCustomerFileInfoOutput>>();
                foreach (var item in image)
                {
                    imagelist.Add(item);
                }
                foreach (var item in image2)
                {
                    imagelist2.Add(item);
                }
                foreach (var item in data)
                {
                    datalist.Add(item);
                }
                if (!(isOk > 0))
                {
                    throw Oops.Oh(ErrorCode.COM1001);
                }
                else
                {
                    _db.CommitTran();
                    return new { ImageList = imagelist, ImageList2= imagelist2, DataList = data };
                }
            }
            catch (Exception ex)
            {
                _db.RollbackTran();
                throw Oops.Bah("错误信息：" + ex);
            }

        }
    }
}
